package com.ruyuan.rapid.core.netty.processor.filter;

import com.ruyuan.rapid.core.context.Context;

/**
 * 过滤器链表的默认实现 虚拟头结点dummyHead
 * @author mac
 */
public class DefaultProcessorFilterChain extends ProcessorFilterChain<Context> {

    private final String id;

    public DefaultProcessorFilterChain(String id) {
        this.id = id;
    }

    /**
     * 虚拟头结点
     */
    AbstractLinkedProcessorFilter<Context> first = new AbstractLinkedProcessorFilter<Context>() {
        @Override
        public boolean check(Context ctx) throws Throwable {
            return true;
        }

        @Override
        public void entry(Context ctx, Object... args) throws Throwable {
            super.fireNext(ctx, args);
        }
    };

    /**
     * 尾结点
     * 初始化的时候尾节点=头结点
     */
    AbstractLinkedProcessorFilter<Context> end = first;

    /**
     * 过滤器是否执行的校验
     * @param ctx
     * @return
     * @throws Throwable
     */
    @Override
    public boolean check(Context ctx) throws Throwable {
        return true;
    }

    /**
     * 真正执行过滤器的方法
     * @param ctx
     * @param args
     * @throws Throwable
     */
    @Override
    public void entry(Context ctx, Object... args) throws Throwable {
        first.transformEntry(ctx, args);
    }

    @Override
    public void setNext(AbstractLinkedProcessorFilter<Context> next) {
        addLast(next);
    }

    @Override
    public AbstractLinkedProcessorFilter<Context> getNext() {
        return first.getNext();
    }

    /**
     * 在链表的头部添加元素
     * @param filter 当前节点
     */
    @Override
    public void addFirst(AbstractLinkedProcessorFilter<Context> filter) {
        filter.setNext(first.getNext());
        first.setNext(filter);
        if (end == first) {
            end = filter;
        }
    }

    /**
     * 在链表的尾部添加元素
     * @param filter
     */
    @Override
    public void addLast(AbstractLinkedProcessorFilter<Context> filter) {
        end.setNext(filter);
        end = filter;
    }

    public String getId() {
        return id;
    }
}
